package org.micode.libs.servlet.interceptor;

import org.micode.common.consts.HttpHeadConsts;
import org.micode.common.domain.base.BaseUserCache;
import org.micode.libs.servlet.utils.HttpContextUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

@Slf4j
public class BaseServiceInterceptor<UT extends BaseUserCache> extends BaseInterceptor {

    protected Class<UT> utType;

    public BaseServiceInterceptor() {
        super();
        Type type = getClass().getGenericSuperclass();
        if (type instanceof ParameterizedType) {
            this.utType = (Class<UT>) ((ParameterizedType) type).getActualTypeArguments()[0];
        }
    }

    protected UT getCurrentUser(HttpServletRequest request) {
        UT user = (UT) request.getAttribute(HttpHeadConsts.REQUEST_USER_KEY);
        if (null == user) {
            return rebuildUser(request);
        }
        return user;
    }

    private UT rebuildUser(HttpServletRequest httpServletRequest) {
        Long userId = 0L;
        String strUserId = httpServletRequest.getHeader(HttpHeadConsts.REQUEST_HEADER_USERID_KEY);
        if (!StringUtils.isEmpty(strUserId)) {
            try {
                userId = Long.parseLong(strUserId.trim());
            } catch(Exception e) {
                userId = 0L;
            }
        }
        String loginApp = httpServletRequest.getHeader(HttpHeadConsts.REQUEST_LOGIN_APP);
        try {
            UT user = this.utType.newInstance();
            user.setUserId(userId);
            user.setLoginApp(loginApp);
            user.setLoginIp(HttpContextUtils.getIp(httpServletRequest));
            return user;
        } catch (InstantiationException | IllegalAccessException e) {
            log.error("Class conversion exception", e);
        }
        return null;
    }

}
